<template>
	<div>
		<!-- 面包屑 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>参数分类</el-breadcrumb-item>
		</el-breadcrumb>

		<el-card>
			<el-alert title="注意,只能为第三级分类" type="warning" :closable="false" show-icon>
			</el-alert>
			<el-row class="cateSet">
				<el-col>
					<span>选择商品分类:</span>
					<!-- 商品级联选择框 -->
					<el-cascader v-model="selectedIds" :options="cateList" expand-trigger="hover" clearable
						:props="CascaderCateProp" @change="handleChange"></el-cascader>
				</el-col>
			</el-row>
			<el-tabs v-model="activeName" @tab-click="handleTabClick" v-show="!isBtnDisable">
				<el-tab-pane label="动态参数" name="many">
					<el-button type="primary" size="mini" :disabled="isBtnDisable" @click="addParamsDialog = true">添加参数
					</el-button>
					<el-table :data="manyData" border>
						<el-table-column type="expand">
							<template slot-scope="scope">
								<el-tag closable type="success" v-for="(item,index) in scope.row.attr_vals" :key="index"
									@close="doDeleteParams(index,scope.row)">{{item}}</el-tag>
								<el-input class="input-new-tag" v-if="scope.row.inputVisible"
									v-model="scope.row.inputValue" ref="saveTagInput" size="small"
									@keyup.enter.native="handleInputConfirm(scope.row)"
									@blur="handleInputConfirm(scope.row)">
								</el-input>
								<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
									New Tag
								</el-button>
							</template>
						</el-table-column>
						<el-table-column type="index"></el-table-column>
						<el-table-column label="参数名称" prop="attr_name"></el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scope">
								<el-button size="mini" type="primary" icon="el-icon-edit"
									@click="showEditDialog(scope.row)">编辑
								</el-button>
								<el-button size="mini" type="danger" icon="el-icon-delete"
									@click="deleteParams(scope.row)">删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="静态属性" name="only">
					<el-button type="primary" size="mini" :disabled="isBtnDisable" @click="addParamsDialog = true">添加属性
					</el-button>
					<el-table :data="onlyData" border>
						<el-table-column type="expand">
							<template slot-scope="scope">
								<el-tag closable type="success" v-for="(item,index) in scope.row.attr_vals" :key="index"
									@close="doDeleteParams(index,scope.row)">{{item}}</el-tag>
								<el-input class="input-new-tag" v-if="scope.row.inputVisible"
									v-model="scope.row.inputValue" ref="saveTagInput" size="small"
									@keyup.enter.native="handleInputConfirm(scope.row)"
									@blur="handleInputConfirm(scope.row)">
								</el-input>
								<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
									New Tag
								</el-button>
							</template>
						</el-table-column>
						<el-table-column type="index"></el-table-column>
						<el-table-column label="属性名称" prop="attr_name"></el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scope">
								<el-button size="mini" type="primary" icon="el-icon-edit"
									@click="showEditDialog(scope.row)">编辑
								</el-button>
								<el-button size="mini" type="danger" icon="el-icon-delete"
									@click="deleteParams(scope.row)">删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>

				</el-tab-pane>
			</el-tabs>
		</el-card>

		<el-dialog :title="'添加'+titleText" :visible.sync="addParamsDialog" width="50%" @close="clearParams">
			<el-form ref="addParamsFormRef" :model="addParamsForm" :rules="addParamsFormRules">
				<el-form-item :label="titleText" prop="attr_name">
					<el-input autocomplete="off" v-model="addParamsForm.attr_name"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="addParamsDialog = false">取 消</el-button>
				<el-button type="primary" @click="addParamsDo">确 定</el-button>
			</div>
		</el-dialog>

		<el-dialog :title="'修改'+titleText" :visible.sync="editParamsDialog" width="50%" @close="clearEditParams">
			<el-form ref="editParamsFormRef" :model="editParamsForm" :rules="editParamsFormRules">
				<el-form-item :label="titleText" prop="attr_name">
					<el-input autocomplete="off" v-model="editParamsForm.attr_name"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="editParamsDialog = false">取 消</el-button>
				<el-button type="primary" @click="editParamsDo">确 定</el-button>
			</div>
		</el-dialog>
	</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				cateList: [],
				CascaderCateProp: {
					label: 'cat_name',
					value: 'cat_id',
					children: 'children'
				},
				selectedIds: [],
				activeName: 'many',
				manyData: [],
				onlyData: [],
				addParamsDialog: false,
				addParamsForm: {
					attr_name: ''
				},
				addParamsFormRules: {
					attr_name: [{
							required: true,
							message: '请输入参数名称',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 5,
							message: '长度在 3 到 5 个字符',
							trigger: 'blur'
						}
					],
				},
				editParamsDialog: false,
				editParamsForm: {},
				editParamsFormRules: {
					attr_name: [{
							required: true,
							message: '请输入参数名称',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 5,
							message: '长度在 3 到 5 个字符',
							trigger: 'blur'
						}
					],
				},
			}
		},
		methods: {
			async getCateList() {
				const {
					data: res
				} = await this.$http.get('categories');
				if (res.meta.status != 200) {
					return this.$message.error("获取商品分类失败");
				}
				this.cateList = res.data;
				console.log(this.cateList);
			},
			async getParamsData() {
				if (this.selectedIds.length !== 3) {
					this.selectedIds = [];
					return
				}
				const {
					data: res
				} = await this.$http.get(`categories/${this.cateId}/attributes`, {
					params: {
						sel: this.activeName
					}
				});

				res.data.forEach(item => {
					item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
					//控制文本框的显示和隐藏
					item.inputVisible = false;
					//文本框中输入值
					item.inputValue = '';
				})

				if (res.meta.status !== 200) {
					return this.$message.error("获取参数列表失败");
				}

				if (this.activeName == 'many') {
					this.manyData = res.data;
				} else {
					this.onlyData = res.data;
				}
			},
			handleChange() {
				this.getParamsData();
				if (this.selectedIds.length !== 3) {
					this.selectedIds = [];
					this.manyData = [];
					this.onlyData = [];
				}

			},
			handleTabClick() {
				this.getParamsData();
			},
			clearParams() {
				this.$refs.addParamsFormRef.resetFields();
			},
			addParamsDo() {
				this.$refs.addParamsFormRef.validate(async (valid) => {
					if (!valid) return
					const {
						data: res
					} = await this.$http.post(`categories/${this.cateId}/attributes`, {
						attr_name: this.addParamsForm.attr_name,
						attr_sel: this.activeName
					});
					if (res.meta.status !== 201) {
						return this.$message.error("添加参数失败");
					}
					this.$message.success("获取参数列表成功");
					this.addParamsDialog = false;
					this.getParamsData();
				})
			},
			async showEditDialog(data) {
				const {
					data: res
				} = await this.$http.get(`categories/${this.cateId}/attributes/${data.attr_id}`, {
					params: {
						attr_sel: this.activeName
					}
				});
				if (res.meta.status !== 200) {
					return this.$message.error("添加参数失败");
				}
				this.editParamsDialog = true;
				this.editParamsForm = res.data;
			},
			editParamsDo() {
				this.$refs.editParamsFormRef.validate(async (valid) => {
					if (!valid) return;
					const {
						data: res
					} = await this.$http.put(
						`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
							attr_name: this.editParamsForm.attr_name,
							attr_sel: this.activeName
						});
					if (res.meta.status !== 200) {
						return this.$message.error("更新失败");
					}
					this.$message.success("更新成功");
					this.editParamsDialog = false;
					this.getParamsData();

				})
			},
			clearEditParams() {
				this.$refs.editParamsFormRef.resetFields();
			},
			deleteParams(row) {
				this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(async () => {
						const {
							data: res
						} = await this.$http.delete(`categories/${data.cat_id}/attributes/${data.attr_id}`);
						if (res.meta.status !== 200) {
							return this.$message.error('删除分类失败');
						}
						this.$message.success('删除分类成功');
						this.getParamsData();
					})
					.catch(() => {
						this.$message({
							type: 'info',
							message: '已取消删除'
						});
					});
			},
			showInput(row) {
				row.inputVisible = true;
				//$nextTick等待元素加载完成
				this.$nextTick(_ => {
					this.$refs.saveTagInput.$refs.input.focus();
				});
			},
			handleInputConfirm(row) {
				if (row.inputValue.trim().length === 0) {
					row.inputValue = '';
					row.inputVisible = false;
					return;
				}
				//保存
				row.attr_vals.push(row.inputValue.trim());
				row.inputValue = '';
				row.inputVisible = false;

				let code=this.saveAttrValue(row);
				code.then((res)=>{
					if (res !== 200) {
					return this.$message.error('更新失败');
					}
					this.$message.success('添加成功');
				}) 
			},
			doDeleteParams(index, row) {
				this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(() => {
						row.attr_vals.splice(index, 1);
						let code=this.saveAttrValue(row);
						code.then((res)=>{
							if (res !== 200) {
							return this.$message.error('删除失败');
							}
							this.$message.success('删除成功');
						}) 

					})
					.catch(() => {
						this.$message({
							type: 'info',
							message: '已取消删除'
						});
					});
			},
			async saveAttrValue(row) {
				const {
					data: res
				} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
					attr_name: row.attr_name,
					attr_sel: row.attr_sel,
					//' '=>空格
					attr_vals: row.attr_vals.join(' ')
				});
				
				if(res.meta.status!==200){
					return 500;
				}
				return 200;
			}
		},
		created() {
			this.getCateList();
		},
		computed: {
			isBtnDisable() {
				if (this.selectedIds.length !== 3) {
					return true;
				} else {
					return false;
				}
			},
			cateId() {
				if (this.selectedIds.length === 3) {
					return this.selectedIds[this.selectedIds.length - 1];
				}
				return null;
			},
			titleText() {
				if (this.activeName === 'many') {
					return '动态参数';
				}
				return '静态属性';
			},

		}
	}
</script>

<style scoped>
	.cateSet {
		margin: 15px 0;
	}

	.el-tag {
		margin: 10px;
	}

	.input-new-tag {
		width: 250px;
	}
</style>
